//
//  LATexttPolylineRenderer.m
//  LAMapBasicDemo
//
//  Created by 罗亮富 on 2018/6/27.
//  Copyright © 2018年 2Bulu. All rights reserved.
//

#import "LATexttPolylineRenderer.h"

@implementation LATexttPolylineRenderer


-(void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context{
    
    
    [super drawMapRect:mapRect zoomScale:zoomScale inContext:context];
    
    //========绘制文字============
    if(!self.text)
        return;
    
    MKMapRect boundRect = self.overlay.boundingMapRect;

    //文字位置
    MKMapPoint p1 = MKMapPointMake(boundRect.origin.x+boundRect.size.width/2,boundRect.origin.y+boundRect.size.height/2);
    double k = CGContextConvertSizeToUserSpace(context, (CGSize){1,1}).width*self.contentScaleFactor;
#if TARGET_OS_IPHONE
    if(!self.font)
        self.font = [UIFont systemFontOfSize:13.0];
    
    UIFont *font = [self.font fontWithSize:self.font.pointSize*k];
    UIColor *c = self.textColor;
    if(!c)
        c = self.strokeColor;
#else
    if(!self.font)
        self.font = [NSFont systemFontOfSize:13.0];
    
    NSFont *font = [NSFont fontWithName:self.font.fontName size:self.font.pointSize*k];
    NSColor *c = self.textColor;
    if(!c)
        c = self.strokeColor;
#endif
    NSDictionary *attri = @{NSFontAttributeName:font,NSForegroundColorAttributeName:c};
    CGSize titleSize = [self.text sizeWithAttributes:attri];
    
    CGPoint p = [self pointForMapPoint:p1];
    CGRect frame = CGRectMake(p.x-titleSize.width/2, p.y-titleSize.height/2, titleSize.width, titleSize.height);
    CGRect backGroundFrame = CGRectInset(frame, -2*k, -2*k);
    
    CGRect mapRectCG = [self rectForMapRect:mapRect];
    if(!CGRectIntersectsRect(mapRectCG, backGroundFrame))
        return;
    
    if(self.textBackgroundColor)
    {
        CGContextSaveGState(context);
        
        CGPathRef path = CGPathCreateWithRoundedRect(backGroundFrame, self.lineJoin*k, self.lineJoin*k, NULL);
        CGContextAddPath(context, path);
        CGContextSetFillColorWithColor(context, self.textBackgroundColor.CGColor);
        CGContextFillPath(context);
        
        CGPathRelease(path);
        CGContextRestoreGState(context);
    }
    
#if  TARGET_OS_IPHONE
    //NSString(NSStringDrawing)的方法属于UIKit，所以要有UIGraphicsPushContext(context);
    UIGraphicsPushContext(context);
    // CGContextRef ctx = UIGraphicsGetCurrentContext();//macos [[NSGraphicsContext currentContext] graphicsPort];
    //  CGContextSetStrokeColorWithColor(ctx, self.strokeColor.CGColor);
    [self.text drawAtPoint:frame.origin withAttributes:attri];
    UIGraphicsPopContext();
#else
    [self.text drawAtPoint:frame.origin withAttributes:attri];
#endif
    
}


@end
